import React from "react";
import { useState, useEffect } from 'react';
import { CRow, CCol, CFormLabel, CFormSelect, CContainer, CCard } from '@coreui/react'
import { CChart } from '@coreui/react-chartjs';
import { useSelector } from 'react-redux'


const StatisticsForecast = () => {
  const [statisticsData, setStatisticsData] = useState([]);
  const [forecastName, setForecastName] = useState([]);
  const [chartData, setChartData] = useState([]);
  const [params, setParams] = useState({
    id_filename: 1,
    statistics_id: 1,
    forecast_id: 1,
    modality: null,
    locality: null,
    });
  const token = useSelector((state) => state.token);

  const localityitems = [
    { id: 0, name: 'КУ' },
    { id: 1, name: '-' },
    { id: 2, name: 'КУ1' },
    { id: 3, name: 'КУ2+' },
    ];

  const localityoptions = localityitems.map(item => ({
    label: item.name,
    value: item.id.toString(),
    }));

    const modalityitems = [
      { id: 0, name: 'Модальность' },
      { id: 1, name: 'РГ' },
      { id: 2, name: 'КТ' },
      { id: 3, name: 'МРТ' },
      { id: 4, name: 'ММГ' },
      { id: 5, name: 'Флг' },
      { id: 6, name: 'Денс' },
      { id: 7, name: 'РХ' },
      { id: 8, name: 'НДКТ' },
      { id: 9, name: 'ПЭТ/КТ' },
    ];

  const modalityoptions = modalityitems.map(item => ({
    label: item.name,
    value: item.id.toString(),
    }));

  const handleModalityChange = (event) => {
    const selectedModalityId = parseInt(event.target.value, 10);
    const selectedModality = modalityitems.find(item => item.id === selectedModalityId);
    if (selectedModality) {
        if (selectedModalityId === 0) {
        setParams(prevParams => ({
            ...prevParams,
            modality: null,
        }));
        } else {
        setParams(prevParams => ({
            ...prevParams,
            modality: selectedModality.name,
        }));
        }
    }
    };

  const handleLocalityChange = (event) => {
    const selectedLocalityId = parseInt(event.target.value, 10);
    const selectedLocality = localityitems.find(item => item.id === selectedLocalityId);
    if (selectedLocality) {
        if (selectedLocalityId === 0) {
        setParams(prevParams => ({
            ...prevParams,
            locality: null,
        }));
        } else {
        setParams(prevParams => ({
            ...prevParams,
            locality: selectedLocality.id,
        }));
        }
    }
    };


  const handleFileChange = (event) => {
    const { value } = event.target;
    setParams(prevParams => ({
      ...prevParams,
      statistics_id: value,
    }));
    fetchData();
    };

  const handleForecastChange = (event) => {
    const { value } = event.target;
    setParams(prevParams => ({
        ...prevParams,
        forecast_id: value,
    }));
    fetchData();
    };

  const fetchFilename = async () => {
    try {
        const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/statistics/filename`,
          {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
          }
        );
        const data = await response.json();
        setStatisticsData(data);
    } catch (error) {
        console.error('Ошибка при получении данных:', error);
    }
    };

  const fetchForecastName = async () => {
    try {
        const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/forecast/forecast_name`,
          {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
          }
        );
        const data = await response.json();
        setForecastName(data);
    } catch (error) {
        console.error('Ошибка при получении данных:', error);
    }
    };

  const fetchData = async () => {
    let url = `${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/forecast/statistics_forecast?`;
    if (params.statistics_id) {
      url += `&statistics_id=${params.statistics_id}`;
    }
    if (params.forecast_id) {
      url += `&forecast_id=${params.forecast_id}`;
    }
    if (params.modality) {
      url += `&modality=${params.modality}`;
    }
    if (params.locality) {
      url += `&locality=${params.locality}`;
    }
  
    try {
      const response = await fetch(url,
        {
          method: 'GET',
          headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${token}`
          },
        }
      );
      const data = await response.json();
      setChartData(data);
    } catch (error) {
      console.error('Ошибка при получении данных:', error);
    }
  };

  useEffect(() => {
    fetchFilename();
    fetchForecastName()
    fetchData();
    }, [params]);

  return (
    <>
      <h1>Факт-прогноз</h1>
      <br></br>
      <CRow>
        <CCol xs={2}>
          <CFormLabel>Файл статистики</CFormLabel>
        </CCol>
        <CCol xs={4}>
          <CFormSelect 
            aria-label="Выберите файл статистики"
            options={statisticsData.map(item => ({
            label: item.filename,
            value: item.id.toString(),
            }))}
            onChange={handleFileChange}
          />
        </CCol>
      </CRow>
      <br></br>
      <CRow>
        <CCol xs={2}>
          <CFormLabel>Файл прогноза</CFormLabel>
        </CCol>
        <CCol xs={4}>
          <CFormSelect 
            aria-label="Выберите файл прогноза"
            options={forecastName.map(item => ({
            label: item.filename,
            value: item.id.toString(),
            }))}
            onChange={handleForecastChange}
          />
      </CCol>
    </CRow>
    <br></br>
    <CRow>
      <CCol xs={2}>
        <CFormLabel>Модальность</CFormLabel>
      </CCol>
      <CCol xs={4}>
        <CFormSelect 
            aria-label="Default select example"
            options={modalityoptions}
            onChange={handleModalityChange}
        />
      </CCol>
    </CRow>
    <br></br>
    <CRow>
      <CCol xs={2}>
        <CFormLabel>КУ</CFormLabel>
      </CCol>
      <CCol xs={4}>
        <CFormSelect 
            aria-label="Default select example"
            options={localityoptions}
            onChange={handleLocalityChange}
        />
      </CCol>
    </CRow>
    <br></br>
    <CRow>
      <CFormLabel>Факт-прогноз количества исследований по неделям</CFormLabel>
    </CRow>
    <CRow>
      <CContainer fluid>
        <CCard>
          <CChart
            type="line"
            data={chartData}
            options={{
              responsive: true,
              stacked: true,
            }}
          />
        </CCard>
      </CContainer>
    </CRow>
    </>
    )
}

export default StatisticsForecast